package class07;

import utils.TreeNode;

import java.util.*;

/**
 * @Description: 二叉树按层遍历
 * @Author: WangWenpeng
 */
public class Code01_二叉树按层遍历 {
    public static List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> ans = new LinkedList<>();
        if (root == null) {
            return ans;
        }
        //队列  用LinkedList做队列      双端队列也可以代替栈
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> curAns = new LinkedList<>();
            //弹出一个就往里放两个子节点  size动态会动
            for (int i = 0; i < size; i++) {
                TreeNode curNode = queue.poll();
                curAns.add(curNode.val);
                if (curNode.left != null) {
                    queue.add(curNode.left);
                }
                if (curNode.right != null) {
                    queue.add(curNode.right);
                }
            }
            //!!!!!!!!!!!!!!!!!!!!!!!
            //都往第一位添加 list会往后挤
            ans.add(0, curAns);
        }
        return ans;
    }


    public static void main(String[] args) {
        TreeNode l3 = new TreeNode(15);
        TreeNode r3 = new TreeNode(7);
        TreeNode r2 = new TreeNode(20, l3, r3);
        TreeNode l2 = new TreeNode(9);
        TreeNode l1 = new TreeNode(3, l2, r2);

        //  [[15, 7], [9, 7], [3]]
        List<List<Integer>> lists = levelOrderBottom(l1);
        System.out.println(lists);
    }
}
